﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Nlp.V20190408;
using TencentCloud.Nlp.V20190408.Models;
using static MyQQRobot.Form1;

namespace MyQQRobot
{
    public class ChatRobot
    {
       static Credential cred=new Credential
        {
            SecretId = "AKIDue7JEtIQHrADzXqtfAOL2TdX9UYLs75m",
            SecretKey = "ScV7SVHm0yg7G9k46sNaW7SVHlzwc1A5"
        };

        public static void answer(String user_number,String msg)
        {
            try
            {
               
                ClientProfile clientProfile = new ClientProfile();
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.Endpoint = ("nlp.tencentcloudapi.com");
                clientProfile.HttpProfile = httpProfile;

                NlpClient client = new NlpClient(cred, "ap-guangzhou", clientProfile);
                ChatBotRequest req = new ChatBotRequest();
                req.Query = msg;
                ChatBotResponse resp = client.ChatBotSync(req);
                RobotResponseInfo robotResponseInfo = JsonConvert.DeserializeObject<RobotResponseInfo>(AbstractModel.ToJsonString(resp));
                Console.WriteLine(AbstractModel.ToJsonString(resp));
                Message resonpseMsg = new Message("private",user_number,robotResponseInfo.Reply);
                sendMsg(resonpseMsg);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            
        }

        public static void sendMsg(Message message)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 5700));     //配置服务器IP：端口    
                Console.WriteLine("连接服务器成功！");
            }
            catch
            {
                Console.WriteLine("连接服务器失败，请按回车键退出！");
                return;
            }
            String payload;
            if (message.Msg_type.Equals("group"))
                payload = "GET /send_group_msg?group_id=" + message.Number + "&message=" + message.Msg + " HTTP/1.1\r\nHost:" + "127.0.0.1" + ":5700\r\nConnection: close\r\n\r\n";
            else
                payload = "GET /send_private_msg?user_id=" + message.Number + "&message=" + message.Msg + " HTTP/1.1\r\nHost:" + "127.0.0.1" + ":5700\r\nConnection: close\r\n\r\n";

            clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(payload));

            clientSocket.Shutdown(SocketShutdown.Both);     //关闭Socket
            clientSocket.Close();
            Console.WriteLine("发送完成");
        }
    }
}
